package com.wanji.gateway.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class CIDRUtil {

    /**
     * 判断 IP 地址是否在 CIDR 格式的网段内
     */
    public static boolean isIpInCidrRange(String ip, String cidr) {
        if (ip == null || cidr == null) {
            return false;
        }
        try {
            String[] parts = cidr.split("/");
            if (parts.length != 2) {
                return false;
            }

            String baseIpStr = parts[0];
            int prefixLength = Integer.parseInt(parts[1]);

            InetAddress baseIp = InetAddress.getByName(baseIpStr);
            InetAddress targetIp = InetAddress.getByName(ip);

            if (baseIp.getClass() != targetIp.getClass()) {
                // IPv4 和 IPv6 不匹配
                return false;
            }

            byte[] baseIpBytes = baseIp.getAddress();
            byte[] targetIpBytes = targetIp.getAddress();

            int bitsToCompare = Math.min(prefixLength, baseIpBytes.length * 8);
            int bytesToCompare = bitsToCompare / 8;
            int remainingBits = bitsToCompare % 8;

            // 比较完整字节
            for (int i = 0; i < bytesToCompare; i++) {
                if (baseIpBytes[i] != targetIpBytes[i]) {
                    return false;
                }
            }

            // 比较剩余位
            if (remainingBits != 0) {
                byte mask = (byte) (0xFF << (8 - remainingBits));
                if ((baseIpBytes[bytesToCompare] & mask) != (targetIpBytes[bytesToCompare] & mask)) {
                    return false;
                }
            }
            return true;
        } catch (UnknownHostException | NumberFormatException e) {
            return false;
        }
    }
}